<script lang="jsx" setup>
import { nextTick, onMounted, ref } from 'vue';
import { isArray } from 'lodash-es';
import { get } from '@/service/api/api';
import underReview from '@/assets/imgs/examine-icon/under-review.png';
import unaudited from '@/assets/imgs/examine-icon/unaudited.png';
import audited from '@/assets/imgs/examine-icon/audited.png';
import { useAuthStore } from '@/store/modules/auth';
import Form from '../form.vue';

const authStore = useAuthStore();

const props = defineProps({
  operateType: {
    type: String,
    default: () => 'add'
  },
  rowData: {
    type: Object,
    default: () => null
  },
  searchUrlObj: {
    type: Object,
    default: () => {
      return {
        moduleNo: '/rcerp/agv/erp/findByModuleNo',
        lotId: '/rcerp/agv/erp/findByLotNo'
      };
    }
  },
  topFormList: {
    type: Array,
    default: () => []
  },
  bottomList: {
    type: Array,
    default: () => []
  },
  transfromRowData: {
    type: Function,
    default: null
  },
  column: {
    type: Array,
    default: () => []
  },
  tableKey: {
    type: String,
    default: () => 'id'
  },
  getTableDataUrl: {
    type: String,
    default: null
  },
  scroll: {
    type: Object,
    default: () => {
      return { x: 'auto', y: 'auto' };
    }
  },
  divider: {
    type: String,
    default: null
  },
  getTableUrlSuffix: {
    type: Object,
    default: null
  },
  tableTitle: {
    type: String,
    default: '质量项目'
  }
});
const fixedList = ref([
  {
    type: 'datePicker',
    key: 'createTime',
    label: '创建时间',
    span: 8,
    disabled: true,
    showTime: true
  },
  {
    type: 'input',
    key: 'create-founder', // 这里这么写是为防止字段重复
    label: '创建人',
    defaultValue: props.rowData?.operator || authStore.userInfo.user.nickName || authStore.userInfo.user.userName,
    disabled: true,
    span: 8
  }
]);

const activeKey = '1';
let returnModelFn;
const model = ref(getModel(props.topFormList));
let bottomList = [...props.bottomList];
if (props.operateType !== 'add') {
  bottomList = [...props.bottomList, ...fixedList.value];
}

const personModle = ref(getModel(bottomList));

function getModel(arr) {
  const obj = {};
  arr.forEach(item => {
    if (item.key) {
      obj[item.key] = item.defaultValue;
      if (props?.rowData) {
        obj[item.key] = props?.rowData?.[item.key];
      }
      if (item.key === 'create-founder') {
        obj[item.key] = item.defaultValue;
      }
    }
    if (item.type === 'getModel') {
      returnModelFn = item.handle;
    }
    if (item.tansfromDisabled) {
      item.disabled = item.tansfromDisabled(props.operateType);
    }
    if (props.searchUrlObj[item.key]) {
      item.handleSearch = (e, val) => {
        let params = {};
        if (item.searchValidate && !item.searchValidate()) {
          return;
        }
        if (item.key === 'lotId') {
          params.lotNumber = val;
        } else {
          params[item.key] = val;
        }
        if (item.searchKey) {
          params[item.searchKey] = val;
        }
        if (item.otherKeyArr) {
          if (isArray(item.otherKeyArr)) {
            item.otherKeyArr.forEach(key => {
              params[key] = model.value[key];
            });
          } else {
            Object.entries(item.otherKeyArr).forEach(([key, value]) => {
              params[key] = model.value[value];
            });
          }
        }

        if (item.otherSearchParams) {
          params = {
            ...params,
            ...item.otherSearchParams
          };
        }

        get(props.searchUrlObj[item.key], params).then(({ data, error }) => {
          if (!error) {
            if (item.transfromSearch) {
              item.transfromSearch(model, data);
              return;
            }
            model.value = data;
          }
        });
      };
    }
  });
  if (props.transfromRowData) {
    return props.transfromRowData(props.rowData, obj);
  }
  return obj;
}

const topFormRef = ref(null);
const bottomFormRef = ref(null);

async function validate() {
  if (props.topFormList.length) {
    await topFormRef.value.validateForm();
  }
  if (props.bottomList.length) {
    await bottomFormRef.value.validateForm();
  }
}

// 表格部分
const tableData = ref([]);
const loading = ref(false);
function getTableData() {
  loading.value = true;
  // const url = `${props.getTableDataUrl}${props.operateType === 'add' ? '' : `?id=${props.rowData.id}`}`;
  let url = '';
  if (props.operateType === 'add') {
    const suffix = props?.getTableUrlSuffix?.add ? props?.getTableUrlSuffix?.add : 'selectBadId';
    url = `${props.getTableDataUrl}${suffix}`;
  } else {
    const suffix = props?.getTableUrlSuffix?.byId ? props?.getTableUrlSuffix?.byId : 'listBad';
    url = `${props.getTableDataUrl}${suffix}?id=${props.rowData.id}`;
  }
  get(url, {})
    .then(({ data, error }) => {
      if (!error) {
        data.forEach((item, index) => {
          item.index = index + 1;
          item.disabled = props.operateType === 'look';
        });

        tableData.value = data;
        console.log('tableData.value :>> ', tableData.value);
        returnModelFn && returnModelFn(model, personModle, tableData, props.operateType);
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

function delRow(row) {
  const index = tableData.value.findIndex(item => item[props.tableKey] === row[props.tableKey]);
  tableData.value.splice(index, 1);
}

if (props.getTableDataUrl && props.column.length) {
  getTableData();
}

onMounted(() => {
  nextTick(() => {
    returnModelFn && returnModelFn(model, personModle, tableData, props.operateType);
  });
});

defineExpose({
  personModle,
  model,
  validate,
  tableData,
  delRow
});
</script>

<template>
  <div class="production-report-form relative w-full">
    <div v-if="props.operateType !== 'add'" class="state">
      <template v-if="props.rowData.state === 0">
        <img :src="unaudited" alt="examine-icon" />
      </template>
      <template v-if="props.rowData.state === 2 || props.rowData.state === 4">
        <img :src="underReview" alt="examine-icon" />
      </template>
      <template v-if="props.rowData.state === 3">
        <img :src="audited" alt="examine-icon" />
      </template>
    </div>

    <template v-if="props.topFormList.length">
      <ATabs v-model:activeKey="activeKey">
        <ATabPane key="1" tab="基本项目"></ATabPane>
      </ATabs>
      <Form ref="topFormRef" v-model:model="model" :form-list="props.topFormList"></Form>
    </template>

    <template v-if="props.column.length">
      <ATabs v-model:activeKey="activeKey">
        <ATabPane key="1" :tab="props.tableTitle"></ATabPane>
      </ATabs>
      <div class="quality-item-table">
        <ATable
          :columns="props.column"
          :data-source="tableData"
          :row-key="props.tableKey"
          :pagination="false"
          :scroll="props.scroll"
          :loading="loading"
          size="small"
          bordered
        ></ATable>
      </div>
    </template>
    <template v-if="props.divider">
      <ADivider>{{ props.divider }}</ADivider>
    </template>
    <template v-if="bottomList.length">
      <ATabs v-model:activeKey="activeKey">
        <ATabPane key="1" tab="状态信息"></ATabPane>
      </ATabs>
      <Form ref="bottomFormRef" v-model:model="personModle" :form-list="bottomList"></Form>
    </template>
  </div>
</template>

<style lang="scss" scoped>
.production-report-form {
  border: 1px solid #ccc;
  padding: 0 30px;
  padding-top: 35px;
  height: 100%;
  overflow: auto;
  position: relative;
  .state {
    position: absolute;
    top: 0;
    right: 100px;
    img {
      height: 80px;
    }
  }
}
</style>
